import { reactive, ref } from 'vue'
import { type _StoreWithState, defineStore } from 'pinia'
import { defaultTheme } from './constants/defaultTheme'

import type { IThemeItem } from './interfaces/theme.interface'

export const useThemeStore = defineStore('theme', () => {
  const darkMode = ref<boolean>(false)
  function toggleDarkMode() {
    darkMode.value = !darkMode.value
  }

  const themeList = reactive<IThemeItem[]>(defaultTheme)
  function reset(this: _StoreWithState<'theme', any, unknown, unknown>) {
    this.$reset()
  }
  function addTheme(theme: IThemeItem) {
    themeList.push(theme)
  }
  function removeTheme(pageId: number) {
    themeList.splice(
      themeList.findIndex((item) => item.pageId === pageId),
      1
    )
  }
  function getThemeByPageId(pageId: number) {
    return themeList.filter((theme) => theme.pageId === pageId)
  }
  function updateTheme(theme: IThemeItem) {
    const start = themeList.findIndex((item) => item.pageId === theme.pageId)
    themeList.splice(start, 1, theme)
  }

  return {
    darkMode,
    toggleDarkMode,

    themeList,
    addTheme,
    removeTheme,
    updateTheme,
    getThemeByPageId,

    reset
  }
})
